package top.noteday.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import entity.field.FieldDto;
import entity.field.FieldQuery;
import entity.field.FieldVo;
import entity.result.EntityResult;
import entity.value.Value;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import top.noteday.dao.field.FieldDao;
import top.noteday.provider.field.FieldService;
import top.noteday.provider.value.ValueService;
import utils.common.StrUtil;
import entity.form.*;
import top.noteday.dao.form.FormDao;
import top.noteday.provider.form.FormService;

@Component
public class FormServiceImpl implements FormService {

	private Logger LOGGER = LoggerFactory.getLogger(FormServiceImpl.class);

	@Autowired
	private FormDao formDao;

	@Autowired
    private FieldService fieldService;
	@Autowired
    private FieldDao fieldDao;
    @Autowired
    private ValueService valueService;

    /*
    @Override
    PageResult<FormDto> selectForm(FormVo formVo, Page page) {
        FormQuery formQuery = new FormQuery();
        PageResult<FormDto> result = new PageResult<>();

        // TODO 设置查询信息
        formQuery.setCreator(userId);
        formQuery.setPage(page);

        // 设置查询条数
        int count = formDao.selectFormCount(formQuery);
        result.setTotalCount(count);

        List<FormDto> list = new ArrayList<>();
        if (count > 0) {
            list = formDao.selectForm(formQuery);

            // 返回值信息缺少时，赋值默认值
            for(CommissionDto dto : list) {
                // TODO 设置返回值默认信息
                //if(StrUtil.isEmpty(dto.getBorrowerPhone())) { dto.setBorrowerPhone(""); }
                //if(StrUtil.isEmpty(dto.getBuildArea())) { dto.setBuildArea(new BigDecimal("0.00")); }
            }
        }

        result.setData(list);
        result.setCode(ResponseCodeEnum.SUCCESS.getCode());
        result.setMess(ResponseCodeEnum.SUCCESS.getMessage());
        result.setSuccess(true);
        return result;
    }
    */

    /**
     * 插入数据
     **/
    @Override
    public Form selectById(Integer id) {
        FormQuery query = new FormQuery();
        query.setId(id);

        List<FormDto> list = formDao.selectByParam(query);

        return StrUtil.isEmpty(list) ? null : list.get(0);
    }


    /**
     * 保存表单模板
     */
    @Override
    @Transactional
    public EntityResult<FormDto> saveFormTemplate(FormVo vo) {
        LOGGER.info("保存表单模板{} = ", vo);
        if (StrUtil.isEmpty(vo.getId())) {
            return this.insertForm(vo);
        }
        return this.updateForm(vo);
    }

    private EntityResult<FormDto> insertForm(FormVo vo) {
        EntityResult<FormDto> result = new EntityResult();
        // 保存表单模板
        vo.setCreator(vo.getUserId());
        vo.setCreateTime(vo.getDate());
        vo.setOperator(vo.getUserId());
        vo.setUpdateTime(vo.getDate());

        if (1 == vo.getActivationType() ) {
            vo.setStatus(1);
            vo.setActivationTime(new Date());
        } else {
            vo.setStatus(1);
        }

        int count = formDao.insert(vo);
        StrUtil.paramIsCorrect(count != 0, "表单模板保存错误");

        // 保存属性
        this.saveFieldList(vo);
        return result;
    }

    private EntityResult<FormDto> updateForm(FormVo vo) {
        EntityResult<FormDto> result = new EntityResult();
        // 保存表单模板
        vo.setOperator(vo.getUserId());
        vo.setUpdateTime(vo.getDate());

        if (1 == vo.getActivationType() ) {
            vo.setStatus(1);
            vo.setActivationTime(new Date());
        } else {
            vo.setStatus(1);
        }

        int count = formDao.updateById(vo);
        StrUtil.paramIsCorrect(count != 0, "表单模板保存错误");

        // 清除之前数据
        fieldService.clearFieldByFormId(vo.getId());
        // 保存属性
        this.saveFieldList(vo);
        return result;
    }

    private void saveFieldList(FormVo vo) {
        // 保存模板属性
        List<FieldVo> fieldList = vo.getFieldList();
        for (int i=0; i<fieldList.size(); i++) {
            FieldVo fieldVo = fieldList.get(i);
            fieldVo.setFormId(vo.getId());
            fieldVo.setMapper("value"+(i+1));
            fieldVo.setUserId(vo.getUserId());
            fieldVo.setDate(vo.getDate());
            fieldService.saveField(fieldVo);
        }
    }

    /**
     * 获取表单模板
     */
    @Override
    public EntityResult<FormDto> getFormTemplate(FormVo vo) {
        LOGGER.info("获取表单模板{} = ", vo);
        EntityResult<FormDto> result = new EntityResult<>();

        // 获取表单数据
        Form form = this.selectById(vo.getId());
        FormDto formDto = new FormDto();
        BeanUtils.copyProperties(form, formDto, "creator","createTime","operator","updateTime","deleted","version");

        // 获取属性数据
        FieldQuery fieldQuery = new FieldQuery();
        fieldQuery.setDeleted(0);
        fieldQuery.setFormId(vo.getId());
        List<FieldDto> fieldDtoList = fieldDao.selectField(fieldQuery);

        Map<String, FieldDto> fieldDtoMap = new HashMap();
        for (FieldDto fieldDto : fieldDtoList) {
            //fieldDtoMap.put(fieldDto.getCode(), getfieldDto);
        }

        formDto.setFieldDtoList(fieldDtoList);

        return result.responseSuccess(formDto);
    }

    /**
     * 提交表单
     */
    @Override
    @Transactional
    public EntityResult<FormDto> submitForm(FormVo vo) {
        LOGGER.info("提交表单{} = ", vo);
        EntityResult<FormDto> result = new EntityResult<>();
        Map<String, String> valueMap = new HashMap<>();

        // 模板获取字段
        FieldQuery fieldQuery = new FieldQuery();
        fieldQuery.setFormId(vo.getFormId());
        List<FieldDto> fieldDtoList = fieldDao.selectField(fieldQuery);

        // 模板对应关系
        Map<String, String> fieldMap = new HashMap();
        for (FieldDto dto : fieldDtoList) {
            fieldMap.put(dto.getCode(), dto.getMapper());
        }
        // 传入数据
        Map<String, String> valueFieldMap = vo.getFieldMap();
        for (Map.Entry<String, String> entry : valueFieldMap.entrySet()) {
            String code = entry.getKey();
            String value = entry.getValue();

            String mapper = fieldMap.get(code);
            if (StrUtil.isEmpty(mapper)) {
                continue;
            }
            valueMap.put(mapper, value);
        }

        Value value = JSONObject.parseObject(JSONObject.toJSONString(valueMap), Value.class);
        value.setFormId(vo.getFormId());

        valueService.saveValues(value);
        return result;
    }
}
